var canvas ;   //获取canvas对象
var ruler ;   //获取标尺
var winW ; //获取当前整个html页面的宽度
var winH ; //获取当前整个html页面的高度
var div ;
var context;                    //根据获取的对象创建画板
var rulerContext;

var btn ;
var canvasW;           //画布的宽
var canvasH;       //画布的高
var rulerH ;          //标尺的高

var xmargin = 10;       //设置x边距
var ymargin = 50;       //设置y边距
var tspixel = 8;            //设置时间的像素间隔
var gap = 120;                  //通道之间的间隔
var gapcp = gap;
var cursor = 50;        //游标的位置
var cursor1 = 250;      //游标的位置
var cursoradd = 0;
var cursorsub = 0;
var cursoradd1 = 0;
var cursorsub1 = 0;
var param;
var lenghtyMargin = 20; //刻度跟y边距之间的距离
var waveData;
var pix = 1;//横向放大倍数
var pixneg = 1;//横向压缩倍数
var pagestart = 0;
var pagelast = 0;
var formatter;//计算特征值对象
var valueArr;//显示的计算值数组
var timeDiff;//游标间的时钟差
var valueColor='blue';
var waveValueWidth;
var beginTime;
var stack = [];
var id;
	
function init(){
    canvas = document.getElementById("main");     //获取canvas对象
    ruler = document.getElementById("ruler");     //获取标尺
    winW = document.documentElement.clientWidth || document.body.clientWidth;  //获取当前整个html页面的宽度
    winH = document.documentElement.clientHeight || document.body.clientHeight;  //获取当前整个html页面的高度
    div = document.getElementById("div");
    div.style.width = winW;
    div.style.height = winH- 28 +"px";

    btn = document.getElementById("btn");
    canvasW = winW-5;           //画布的宽
    canvasH = winH;         //画布的高
    canvas.width = canvasW;  
    ruler.width = canvasW;
    rulerH =canvasH-16;            //标尺的高
    ruler.height = rulerH;  
    waveValueWidth = winW-200;
    
    btn.addEventListener('mousedown', function(e) {
　　　　        event.preventDefault();// 阻止浏览器默认事件
        var target = e.target;
        id = target.getAttribute("id");
        document.getElementById(id).src="static/img/"+id+"2.png";
    }, false);
    btn.addEventListener('mouseup', function(e) {
　　　　        event.preventDefault();// 阻止浏览器默认事件
        document.getElementById(id).src="static/img/"+id+".png";
        switch (id){
            case "zoomOutButton":       //时间放大
                zoomH(true);
                break;
            case "zoomInButton" :       //时间缩小
                zoomH(false);
                break;
            break;
            case "zoomOutaisle":        //通道放大
                zoomV(10);
                break;
            case "zoomInaisle":         //通道缩小
                zoomV(-10);
                break;
            case "zoomleft":        //向左
                moveLeft();
                break;
            case "zoomright":   //向右
                moveRight();
                break;
            case "cursorleft":      //游标向左
                cursor-=10;
                break;
            case "cursorright":     //游标向右
                cursor+=10;
                break;
            case "cursorleft1":     //游标向左
                cursor1-=10;
                break;
            case "cursorright1":        //游标向右
                cursor1+=10;
                break;
            case "close":       //关闭
                window.close();
                break;
            case "restore":         //还原
                pixneg = 1;
                pix = 1;
                gap = 120;
                pagestart = 0;
                pagelast = stack[0];
                stack = [];
                break;
            case "exportButton":        //导出PNG图片
                exportPNG();
                break;
        }
        Interface(waveData);
    })
    //左游标
    canvasDiv = document.getElementById('blueLine');
    blue = document.getElementById('blue');
    canvasDiv.style.left=(cursor-10)+'px';
    canvasDiv.style.top=(ymargin+lenghtyMargin+15)+'px';
    canvasDiv.style.height=(canvasH-ymargin-lenghtyMargin)+'px';
    var blueLineThicknessSign = 0;
    var greenLineThicknessSign = 0;
    var blueLineClickSign = 0;
    var greenLineClickSign = 0;
    canvasDiv.addEventListener('mouseover', function(event) {
         if (greenLineThicknessSign == 0) {
            blueLineThicknessSign = 1;
            drawvalue(waveData,true);
            blue.style.width="2px";
         }
    })
    canvasDiv.addEventListener('mouseout', function(event) {
        blueLineThicknessSign = 0;
         blue.style.width="1px";
    })
    canvasDiv.addEventListener('mousedown', function(event) {
        if (greenLineClickSign == 0) {
            blueLineClickSign = 1;
         }
    })
    canvasDiv.addEventListener('mouseup', function(event) {
        blueLineClickSign = 0;
    })
    document.getElementById('abc').addEventListener('mousemove', function(event) {
        //console.log(event);
        if(blueLineClickSign == 1){
            var xL=event.pageX-10;
            var x=parseInt(xL);
            cursor = x+2;
            document.getElementById('blueLine').style.left=x+'px';  
            drawvalue(waveData,true);
        }else if(greenLineClickSign == 1){
            var xL=event.pageX-10;
            var x=parseInt(xL);
            cursor1 = x+2;
            document.getElementById('greenLine').style.left=x+'px'; 
            drawvalue(waveData,false);
        }
    })

    //右游标
    canvasDiv = document.getElementById('greenLine');
    green = document.getElementById('green');
    canvasDiv.style.left=(cursor1-10)+'px';
    canvasDiv.style.top=(ymargin+lenghtyMargin+15)+'px';
    canvasDiv.style.height=(canvasH-ymargin-lenghtyMargin)+'px';

    canvasDiv.addEventListener('mouseover', function(event) {
         if (blueLineThicknessSign == 0) {
            greenLineThicknessSign = 1;
            drawvalue(waveData,true);
            green.style.width="2px";
         }
    })
    canvasDiv.addEventListener('mouseout', function(event) {
        greenLineThicknessSign = 0;
         green.style.width="1px";
    })
    canvasDiv.addEventListener('mousedown', function(event) {
        if (blueLineClickSign == 0) {
            greenLineClickSign = 1;
         }
    })
    canvasDiv.addEventListener('mouseup', function(event) {
        greenLineClickSign = 0;
    })
    //显示工具栏
    spreadright = document.getElementById('spreadright');
    hidileft = document.getElementById('hidileft');
    tongdao = document.getElementById('tongdao');
    spreadright.addEventListener('click', function(event) {
　　　　        event.preventDefault();// 阻止浏览器默认事件
        spreadright.style.display = "none";
        hidileft.style.display = "block";
        btn.style.display = "block";
        tongdao.style.display = "block";
    }, false);
    //隐藏工具栏
    hidileft.addEventListener('click', function(event) {
        event.preventDefault();// 阻止浏览器默认事件
        spreadright.style.display = "block";
        hidileft.style.display = "none";
        btn.style.display = "none";
        tongdao.style.display = "none";
    }, false);
    //禁止父窗口滚动
    $.fn.scrollUnique = function() {
        return $(this).each(function() {
            var eventType = 'mousewheel';
            if (document.mozHidden !== undefined) {
                eventType = 'DOMMouseScroll';
            }
            $(this).on(eventType, function(event) {
                var scrollTop = this.scrollTop,
                    scrollHeight = this.scrollHeight,
                    height = this.clientHeight;

                var delta = (event.originalEvent.wheelDelta) ? event.originalEvent.wheelDelta : -(event.originalEvent.detail || 0);        

                if ((delta > 0 && scrollTop <= delta) || (delta < 0 && scrollHeight - height - scrollTop <= -1 * delta)) {
                    this.scrollTop = delta > 0? 0: scrollHeight;
                    event.preventDefault();

                }        
            });
        }); 
    };
    $("#div").scrollUnique();
}

window.onresize = function(){
        init();
        Interface(waveData);
    }

var Interface = function(result, formatterPar){		//对外的接口
	waveData = result;
	var res = result.chns;		//获得所有通道
	var height = gap;
	for(var j=0;j<res.length;j++){
	   height = gap*(j+2);
	}
	formatter = new ValueFormatter(result);
	canvasH = height+ymargin; 
	canvas.height = canvasH;   
	scroll.width = canvasW;
    timeDiff = result.ts[getPointPos(cursor1)]-result.ts[getPointPos(cursor)];
    beginTime = result.beginTime;
	var strArray = beginTime.split(".");
	beginTime = strArray[0];
    tsArray = new Array();              
    allArray = new Array();
    context = canvas.getContext("2d");
    context.clearRect(xmargin,ymargin,canvasW,canvasH);//清除画布上的指定区域
    startdraw(result);          //开始画

    rulerContext = ruler.getContext("2d");
    rulerContext.clearRect(0,0,canvasW,rulerH);//清除画布上的指定区域
    rulerStartdraw(result);         //画标尺
	document.getElementById("blueLine").style.display = "block";
	document.getElementById("greenLine").style.display = "block";
}
//根据屏幕位置获得采样点位置
function getPointPos(cur){
    var pos=0;
    if(pix>1){//横向放大
        //pos = pagestart+cur/pix-xmargin;
        pos = pagestart+parseInt((cur-xmargin)/pix);
    }
    else{
        //pos = pagestart+cur*pixneg-xmargin;
        pos = pagestart+(cur-xmargin)*pixneg;
    }
    return pos;
}

function rulerParameter(result){			
}
function rulerStartdraw(result){
	outline(rulerContext,canvasW,rulerH);	
		legend(result,rulerContext);		//画时间毫秒
}
//画轮廓
function startdraw(result){
	 //outline(context,canvasW,canvasH);			
    // legend(result,context);		//画时间毫秒
     drawwave(result,context);			//画波形
}
//画波形
function drawwave(result,cont){				
	var chns = result.chns;
    //alert(chns[4].name);
    var maxsv= [];
    var maxsi= [];
	var maxs = [];
    var max = 0;
	var boo = true;
	if(chns.length>=4){
		boo = false;
		for(var i=0;i<chns.length;i++){
            if(chns[i].uu=="V"){
                maxsv.push(Math.max.apply(Math,chns[i].y));
            }else if(chns[i].uu=="A"){
                maxsi.push(Math.max.apply(Math,chns[i].y));
            }else{
                max = 10;
            }
			
		}
	}
	var maxi = Math.max.apply(Math,maxsi);
    var maxv = Math.max.apply(Math,maxsv);
	var str = "";
	var strName = "";
	var aParam = "";
	if(winW<380)
		aParam="width:150px;";
    var curs = cursor;
	if(valueColor=='green')
		curs = cursor1;
 	valueArr = formatter.getValueDataByIndex(getPointPos(curs),false);
    //console.log("valueArr");
    //console.info(valueArr);
	for(var i=0;i<chns.length;i++){
		var k = 0;
		var bad = (gapcp-gap)/gapcp;
		var line = i*gap+ymargin+65*bad;
		if(line<ymargin+100){
			line = i*100+ymargin;
		}
    	var diff = (chns[i].cursor1-chns[i].cursor)/1000;
        var valueOjb = undefined;
        for (var k = 0; k < valueArr.length; k++) {
            if(valueArr[k].index === i) {
                valueOjb = valueArr[k];
            }
        }
		strName+="<div style='position:absolute;"+aParam+"top:"+(line-18)+"px;left:"+xmargin+"px;font-size: 14px;color:#fff'>"+chns[i].name+"</div>"
		if(valueOjb){
            var a = valueOjb.valueStr;
			var b = valueOjb.valueSsz;
		    var re = /([0-9]+\.[0-9]{2})[0-9]*/;
		    a = a.replace(re,"$1");
		    b = b.toFixed(2);
			var value = ' 有效:'+a+' 瞬时:'+b;
            str += "<div style='position:absolute;top:"+(line-18)+"px;left:"+(waveValueWidth+30)+"px;font-size: 14px;color:"+valueColor+"'>"+value+"</div>";
        }
		drawwavecan(cont,xmargin,line+1,canvasW-xmargin,line+1,"#ccc");			//画分割线
		drawwavecan(cont,xmargin,line-15,canvasW-xmargin,line-15,"#ccc");			//画分割线
		drawwavecanvas(cont,xmargin,line+gap/2-7,canvasW,line+gap/2-7);		//画虚线
		var ypoint = chns[i].y;
		if(boo){
			max = Math.max.apply(Math,ypoint);
		}
        if(chns[i].uu=="V"){
            max = maxv;
        }else if(chns[i].uu=="A"){
            max = maxi;
        }else{
            max = Math.max.apply(Math,ypoint);
            max = max*2;
        }
    	cont.beginPath();
    	cont.lineWidth = 1;
        cont.strokeStyle = "#f00";
		cont.moveTo(0+xmargin,line+gap/2-7);
		for(var j=pagestart;j<ypoint.length;j++){
			if(ypoint[j+1] != undefined &&j%pixneg==0){
				var yvalue = line+gap/2-7;	
				var ratio = gap/3;			//通道之间的间隔比例
				var endx = k+1;
				var endy = yvalue;
				var y = yvalue;
				if(ypoint[j+1]){
    				y = yvalue+ypoint[j]/max*ratio;
    				endy = yvalue-ypoint[j+1]/max*ratio;
				}else if(ypoint[j]){
					y = yvalue+ypoint[j]/max*ratio;
				}
				if(k<=canvasW-xmargin*2){
					cont.lineTo(endx+xmargin,endy);
					pagelast = j;
				}
				k+=pix;
			}
			
		}
		cont.stroke(); 
    	cont.closePath();
	}
	document.getElementById('waveName').innerHTML=strName;
	document.getElementById('waveValue').innerHTML=str;
    canvasDivH = document.getElementById("main").offsetHeight;
}
//画虚线
function drawwavecanvas(cont,x,y,endx,endy){			
	cont.beginPath();
	cont.lineWidth = 1;
    cont.strokeStyle = "#bbb";
    for(var i=0;i<endx-xmargin*2;i++){
    	if(i%(tspixel*2)==0){
    		cont.moveTo(x+i,y);
        	cont.lineTo(x+i+tspixel,endy);
            cont.stroke(); 
    	}
    }
	cont.closePath();
}
//画波形的方法
function drawwavecan(cont,x,y,endx,endy,color,lineWidth){		
	cont.beginPath();
	cont.lineWidth = lineWidth||1;
    cont.strokeStyle = color;
    cont.moveTo(x,y);
	cont.lineTo(endx,endy);
    cont.stroke(); 
	cont.closePath();
}
//画要展示的时间的方法
function legend(result,cont){			
    var info = "开始时间:"+beginTime+"    时标差:"+timeDiff/1000+"ms";	
    var str = "<div style='position:absolute;top:"+(ymargin-lenghtyMargin-30)+"px;left:"+xmargin+"px;font-size: 12px;color:#fff'>"+info+"</div>";
    document.getElementById('rulerTime').innerHTML=str;
    var ts = result.ts;		//获得时间坐标
    var k = 0;
    var tf = true;
    var str2 = "";
    for(var j=pagestart;j<ts.length;j++){
    	if(ts[j+1]){
    		if(j%100==0){
    			tf = false;
    			if(k<=canvasW-xmargin*2){
    				if(j%(pixneg*100)==0){
    					tf=true;
    					str2 += "<div style='position:absolute;top:"+(ymargin-18)+"px;left:"+k+"px;font-size: 10px;color:#fff'>"+ts[j]/1000+"</div>";
    				}
    			}
    		}
    		if(tf){
    			if(k==cursor){
            		cursor = cursor==0? j+150:cursor;
    				cursor1 = cursor1==0? j+300:cursor1;
    			}
    			if(k==cursor+10){
    				cursoradd = j;
    			}
    			if(k==cursor-10){
    				cursorsub = j;
    			}
    			if(k==cursor1+10){
    				cursoradd1 = j;
    			}
    			if(k==cursor1-10){
    				cursorsub1 = j;
    			}
    			k+=pix;
    		}
    	}
    }
    document.getElementById('nonius').innerHTML=str2;
}
//在canvas中写字符串
function filltext(size,text,x,y,cont){			
	cont.font =size+"px Times New Roman";  	
    cont.fillText(text, x, y);
}
//画轮廓
function outline(cont,x,y){         
    cont.beginPath();
    cont.lineWidth = 2;
    cont.strokeStyle = "#005588";
    cont.moveTo(xmargin,ymargin);        
    cont.lineTo(xmargin,y);           
    cont.lineTo(x-xmargin,y);    
    cont.lineTo(x-xmargin,ymargin);
    cont.stroke();
    cont.moveTo(xmargin,ymargin+lenghtyMargin);
    cont.lineTo(x-xmargin,ymargin+lenghtyMargin);
    cont.stroke();   
    cont.closePath();
    for(var i=xmargin;i<x-xmargin;i++){		//遍历每个像素
		if(i%5==0){
			if(i%tspixel==0){
				mscoordinates(cont,i,ymargin+lenghtyMargin,8);
			}
		}else{
			if(i%tspixel==0){
				mscoordinates(cont,i,ymargin+lenghtyMargin,4);
			}
		}
    }
}
function mscoordinates(cont,x,y,value){				//画毫秒坐标格子
	cont.beginPath();
	cont.lineWidth = 2;
    cont.strokeStyle = "#005588";
	cont.moveTo(x,y);
	cont.lineTo(x,y-value);
    cont.stroke(); 
	cont.closePath();
}
function zoomH(step){
    if(step){
        if(pix<5){
            if(pixneg>1){
                pixneg--;
            }else{
                pix++;
            }
        }
    }
    else{
        if(pix>-5){
            if(pix>1){
                pix--;
            }else{
                pixneg++;
            }
        }
    }

}
function zoomV(step){
    if(step>0){
        if(gap<150)
            gap+=step;
    }else{
        if(gap>70)
            gap+=step;
    }       
}
function moveLeft(){
    var value = pagelast-pagestart;
    var last = stack.pop();
    var start = stack.pop();
    if(last){
        pagelast = last;
        pagestart = start;
    }
}
//
function moveRight(){
    if(pagelast+10<waveData.chns[0].y.length){
        stack.push(pagestart);
        pagestart = pagelast;
        stack.push(pagelast);
    }
}
        function zoomtwo(x,y,width,heigth,moveleft,time){
    context.clearRect(x,y,width,heigth);//清除画布上的指定区域
    startdraw(param,moveleft,time); 
}
//移动游标重画有效值
function drawvalue(result,boo){
    var timeDiff = result.ts[getPointPos(cursor1)]-result.ts[getPointPos(cursor)];
    var info = "开始时间:"+beginTime+"    时标差:"+timeDiff/1000+"ms";
    var str = "<div style='position:absolute;top:"+(ymargin-lenghtyMargin-30)+"px;left:"+xmargin+"px;font-size:12px'>"+info+"</div>";
    document.getElementById('rulerTime').innerHTML=str;     
    var chns = result.chns;
    var paramNum = cursor;
    valueColor = 'blue';
    if(!boo){
        paramNum = cursor1;
        valueColor = 'green';
    }
    var valueArr = formatter.getValueDataByIndex(getPointPos(paramNum),false);
    var str= "";
    for(var i=0;i<chns.length;i++){
        var k = 0;
        var bad = (gapcp-gap)/gapcp;
        var line = i*gap+ymargin+65*bad;
        if(line<ymargin+100){
            line = i*100+ymargin;
        }
        
        if(chns[i].analyse){
            var a = valueArr[i].valueStr;
            var b = valueArr[i].valueSsz;
            var re = /([0-9]+\.[0-9]{2})[0-9]*/;
            a = a.replace(re,"$1");
            b = b.toFixed(2);
            var value = ' 有效:'+a+' 瞬时:'+b;
            str += "<div style='position:absolute;top:"+(line-18)+"px;left:"+(waveValueWidth+30)+"px;font-size: 14px;color:"+valueColor+"'>"+value+"</div>";
        }
    }
    document.getElementById('waveValue').innerHTML=str;
}
window.Interface = Interface;
window.Init = init;

 
